package memoriaintermedia;

import java.util.Random;
import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableModel;

public class JFrameMemoriaIntemedia extends javax.swing.JFrame {
    Thread hilo;
    Random r;
    int numBloquesDisco;
    int numBloquesMemoria;
    Pagina[] paginasDisco;
    Pagina[] paginasMemoria;
    DefaultTableModel modeloDisco;
    DefaultTableModel modeloMemoria;
    boolean[] EstaEnMemoria;
    DiscoDuro disco;
    NuevoGestorMemoria gestorMemoria;
    
    public JFrameMemoriaIntemedia() {
        initComponents();
        r = new  Random();
        hilo = new  Thread();
        hilo.start();
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        jLabel2 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        txt_bloquesDisco = new javax.swing.JTextField();
        txt_bloquesMemoria = new javax.swing.JTextField();
        jButton1 = new javax.swing.JButton();
        jScrollPane1 = new javax.swing.JScrollPane();
        tabla_disco = new javax.swing.JTable();
        jScrollPane2 = new javax.swing.JScrollPane();
        tabla_memoria = new javax.swing.JTable();
        jLabel4 = new javax.swing.JLabel();
        jLabel5 = new javax.swing.JLabel();
        btn_subirBloque = new javax.swing.JButton();
        lbl_numPaginasMemoria = new javax.swing.JLabel();
        jLabel6 = new javax.swing.JLabel();
        btn_desclavar = new javax.swing.JButton();
        btn_salir = new javax.swing.JButton();
        btn_modificar = new javax.swing.JButton();
        btn_clavar = new javax.swing.JButton();
        btn_escribir = new javax.swing.JButton();
        btn_borrar = new javax.swing.JButton();
        jLabel7 = new javax.swing.JLabel();
        jLabel1 = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("Alumno: Javier Quispe Alcca");
        setResizable(false);

        jPanel1.setBackground(new java.awt.Color(153, 153, 255));

        jLabel2.setText("Número de bloques para el Disco Duro");

        jLabel3.setText("Número de bloques para la Memoria Intermedia:");

        jButton1.setText("Aceptar");
        jButton1.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                jButton1MouseClicked(evt);
            }
        });

        tabla_disco.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {},
                {},
                {},
                {}
            },
            new String [] {

            }
        ));
        jScrollPane1.setViewportView(tabla_disco);

        tabla_memoria.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {},
                {},
                {},
                {}
            },
            new String [] {

            }
        ));
        jScrollPane2.setViewportView(tabla_memoria);

        jLabel4.setText("Páginas del Disco Duro");

        jLabel5.setText("Páginas de la Memoria Intermedia");

        btn_subirBloque.setText("Subir Bloque");
        btn_subirBloque.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                btn_subirBloqueMouseClicked(evt);
            }
        });

        lbl_numPaginasMemoria.setText("COLA");

        jLabel6.setText("Cola LRU:");

        btn_desclavar.setText("Desclavar Bloque");
        btn_desclavar.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                btn_desclavarMouseClicked(evt);
            }
        });
        btn_desclavar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btn_desclavarActionPerformed(evt);
            }
        });

        btn_salir.setText("Salir");
        btn_salir.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                btn_salirMouseClicked(evt);
            }
        });
        btn_salir.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btn_salirActionPerformed(evt);
            }
        });

        btn_modificar.setText("Modificar Bloque");
        btn_modificar.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                btn_modificarMouseClicked(evt);
            }
        });
        btn_modificar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btn_modificarActionPerformed(evt);
            }
        });

        btn_clavar.setText("Clavar Bloque");
        btn_clavar.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                btn_clavarMouseClicked(evt);
            }
        });

        btn_escribir.setText("Escribir en Disco");
        btn_escribir.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                btn_escribirMouseClicked(evt);
            }
        });
        btn_escribir.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btn_escribirActionPerformed(evt);
            }
        });

        btn_borrar.setText("Borrar");
        btn_borrar.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                btn_borrarMouseClicked(evt);
            }
        });
        btn_borrar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btn_borrarActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(lbl_numPaginasMemoria, javax.swing.GroupLayout.DEFAULT_SIZE, 871, Short.MAX_VALUE)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addGroup(javax.swing.GroupLayout.Alignment.LEADING, jPanel1Layout.createSequentialGroup()
                                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addComponent(jLabel3)
                                    .addComponent(jLabel2))
                                .addGap(10, 10, 10)
                                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addComponent(txt_bloquesDisco, javax.swing.GroupLayout.PREFERRED_SIZE, 110, javax.swing.GroupLayout.PREFERRED_SIZE)
                                    .addComponent(txt_bloquesMemoria, javax.swing.GroupLayout.PREFERRED_SIZE, 110, javax.swing.GroupLayout.PREFERRED_SIZE))
                                .addGap(18, 18, 18)
                                .addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 98, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                .addComponent(btn_borrar, javax.swing.GroupLayout.PREFERRED_SIZE, 98, javax.swing.GroupLayout.PREFERRED_SIZE))
                            .addGroup(javax.swing.GroupLayout.Alignment.LEADING, jPanel1Layout.createSequentialGroup()
                                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addComponent(jLabel4)
                                    .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 360, javax.swing.GroupLayout.PREFERRED_SIZE))
                                .addGap(18, 18, 18)
                                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addComponent(jLabel5)
                                    .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 357, javax.swing.GroupLayout.PREFERRED_SIZE))))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 12, Short.MAX_VALUE)
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                            .addComponent(btn_desclavar, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addComponent(btn_salir, javax.swing.GroupLayout.PREFERRED_SIZE, 98, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(btn_modificar, javax.swing.GroupLayout.DEFAULT_SIZE, 124, Short.MAX_VALUE)
                            .addComponent(btn_subirBloque, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addComponent(btn_clavar, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addComponent(btn_escribir, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))
                    .addComponent(jLabel6))
                .addContainerGap())
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGap(22, 22, 22)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jLabel2)
                            .addComponent(txt_bloquesDisco, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jLabel3)
                            .addComponent(txt_bloquesMemoria, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
                    .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 48, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addComponent(btn_salir, javax.swing.GroupLayout.PREFERRED_SIZE, 48, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addComponent(btn_borrar, javax.swing.GroupLayout.PREFERRED_SIZE, 48, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addGap(18, 18, 18)
                .addComponent(jLabel6)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(lbl_numPaginasMemoria)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel4)
                    .addComponent(jLabel5))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 411, Short.MAX_VALUE)
                    .addComponent(jScrollPane2, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 411, Short.MAX_VALUE)
                    .addGroup(javax.swing.GroupLayout.Alignment.LEADING, jPanel1Layout.createSequentialGroup()
                        .addComponent(btn_subirBloque, javax.swing.GroupLayout.PREFERRED_SIZE, 33, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(btn_modificar, javax.swing.GroupLayout.PREFERRED_SIZE, 33, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(btn_clavar, javax.swing.GroupLayout.PREFERRED_SIZE, 33, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(btn_desclavar, javax.swing.GroupLayout.PREFERRED_SIZE, 33, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(btn_escribir, javax.swing.GroupLayout.PREFERRED_SIZE, 33, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap())
        );

        jLabel7.setBackground(new java.awt.Color(255, 255, 255));
        jLabel7.setForeground(new java.awt.Color(255, 51, 0));
        jLabel7.setText("Nota: Para la mejor compresión de este trabajo se requiere la explicación del alumno en clase (se corrigieron los errores del GestorMemoriaIntermedia)");

        jLabel1.setBackground(new java.awt.Color(153, 153, 0));
        jLabel1.setFont(new java.awt.Font("Tahoma", 0, 24));
        jLabel1.setForeground(new java.awt.Color(102, 102, 255));
        jLabel1.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        jLabel1.setText("Aplicación con el gestor de Memoria Intermedia");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addContainerGap()
                        .addComponent(jLabel7))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(43, 43, 43)
                        .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 523, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(21, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 41, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jLabel7, javax.swing.GroupLayout.PREFERRED_SIZE, 14, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(19, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void jButton1MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jButton1MouseClicked
        try {
            numBloquesDisco = Integer.parseInt(txt_bloquesDisco.getText());
            numBloquesMemoria = Integer.parseInt(txt_bloquesMemoria.getText());
            if (numBloquesDisco < numBloquesMemoria)
                JOptionPane.showMessageDialog(null, "La cantidad de bloques del disco deben \n ser mayores a los de la Memoria Intermedia...","ERROR",0);
            else{//datos correctos
                String [] encabezado = {"Índice","NumPágina", "Contenido"};
                modeloDisco = new DefaultTableModel(encabezado, 0);
                modeloMemoria = new DefaultTableModel(encabezado, 0);
 
                paginasDisco = new Pagina[numBloquesDisco];
                for (int i = 0; i < paginasDisco.length; i++) {
                    Pagina pagina = new Pagina(i, "p" + i);
                    paginasDisco[i] = pagina;
                    Object[] o = {i, pagina.getNumeroPagina(),pagina.getDatos()};                    
                    modeloDisco.addRow(o);
                }               
                disco = new DiscoDuro(paginasDisco, numBloquesDisco);
                tabla_disco.setModel(modeloDisco);
                tabla_memoria.setModel(modeloMemoria);
                EstaEnMemoria = new  boolean[numBloquesDisco];
                gestorMemoria = new NuevoGestorMemoria(numBloquesMemoria, disco);
           }
        } catch (Exception e) {
            JOptionPane.showMessageDialog(null, "Los datos de entrada son números enteros...","ERROR",0);
//            JOptionPane.showMessageDialog(null, e.toString()    ,"ERROR",0);
        }
    }//GEN-LAST:event_jButton1MouseClicked
    private void MostrarDatosDeDisco(){
       String [] encabezado = {"Índice","NumPágina", "Contenido"};
         modeloDisco = new DefaultTableModel(encabezado, 0);
       for (int i = 0; i < disco.getNumPaginasDisco(); i++) {
           Pagina p = disco.getPaginas()[i];
            Object[] o = {i, p.getNumeroPagina(),p.getDatos()};                    
            modeloDisco.addRow(o);
        }
        tabla_disco.setModel(modeloDisco);
    }
    private void MostrarDatosDeMemoria(){
        String [] encabezado = {"Índice","NumPágina", "Contenido"};
        modeloMemoria = new DefaultTableModel(encabezado, 0);
        for (int i = 0; i <= gestorMemoria.getPosUltPaginaColocada(); i++) {
           Pagina p = gestorMemoria.getBuffer()[i];
            Object[] o = {i, p.getNumeroPagina(),p.getDatos()};                    
            modeloMemoria.addRow(o);
        }
        tabla_memoria.setModel(modeloMemoria);
    }
    
    private void btn_subirBloqueMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_btn_subirBloqueMouseClicked
        try {//1.- agregamos aleatoriamente bloques a la memoria   
            int aux = r.nextInt(disco.getNumPaginasDisco());
           Pagina pAleatorio = disco.getPaginas()[aux];
           Pagina Paux = new Pagina(pAleatorio.getNumeroPagina(),pAleatorio.getDatos());
           Pagina p = gestorMemoria.ponerPaginaEnBuffer(Paux);
           if(p != null){//actualizamos la pagina en el disco
               disco.getPaginas()[p.getNumeroPagina()] = p;
           }
           MostrarDatosDeDisco();
           MostrarDatosDeMemoria();
           String cola = gestorMemoria.getColaLRU().toString();
           lbl_numPaginasMemoria.setText(cola);
        
        } catch (Exception e) {
            JOptionPane.showMessageDialog(null,e.toString() ,"ERROR",0);
            //"Tiene que seguir los pasos previos..."
        }
    }//GEN-LAST:event_btn_subirBloqueMouseClicked

    private void btn_desclavarMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_btn_desclavarMouseClicked
        // TODO add your handling code here:
    }//GEN-LAST:event_btn_desclavarMouseClicked

    private void btn_salirMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_btn_salirMouseClicked
        // TODO add your handling code here:
    }//GEN-LAST:event_btn_salirMouseClicked

    private void btn_salirActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btn_salirActionPerformed
        System.exit(0);
        
    }//GEN-LAST:event_btn_salirActionPerformed
    private boolean HayBloquesParaModificar(){
        boolean hay = false;
        for (int i = 0; i <= gestorMemoria.getPosUltPaginaColocada(); i++) {
            if (!gestorMemoria.getModifico()[i]) {
                hay = true;
                break;
            }
        }
        return hay;
    }
    private void btn_modificarMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_btn_modificarMouseClicked
        try {
            if(HayBloquesParaModificar()){
                int pos = 0;
                //buscamos una pagina aleatoriamente para modificar
                while (true){
                     pos = r.nextInt(gestorMemoria.getPosUltPaginaColocada() + 1);
                     if (!gestorMemoria.getModifico()[pos]) {
                        break;
                     }
                }
                Pagina p = gestorMemoria.getBuffer()[pos];
                String op ="qwertyuiopasdfghjklñzxcvbnm";
                String dato ="";
                //longitud del dato
                int lon = r.nextInt(20) + 1;
                for (int i = 1; i <= lon; i++) {
                    int aux = r.nextInt(op.length());
                    dato += op.substring(aux, aux+1);
                }
                gestorMemoria.ModificarPagina(p.getNumeroPagina(), dato);
                MostrarDatosDeMemoria();
                MostrarDatosDeDisco();
                String cola = gestorMemoria.getColaLRU().toString();
                lbl_numPaginasMemoria.setText(cola);
            
            }
            else{
                JOptionPane.showMessageDialog(null,"Todos los bloques han sido modificados\n"
                                                 + "y se requiere que se escriban en el disco..." ,"IMPORTANTE",0);
            }
        } catch (Exception e) {
            JOptionPane.showMessageDialog(null,"No realizó los pasos previos para esta operación..." ,"ERROR",0);
        }
    }//GEN-LAST:event_btn_modificarMouseClicked

    private void btn_clavarMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_btn_clavarMouseClicked
        try {
            //buscar un bloque que no esté clavado
            //escoger aleatoriamente un bloque
            //ver si necesita actiualizar en disco
             boolean hay = false;
            for (int i = 0; i <= gestorMemoria.getPosUltPaginaColocada(); i++) {
                if (!gestorMemoria.getEstaClavado()[i]) {
                    hay = true;
                    break;
                }
            }
            if (hay){
              int pos = 0;
                //buscamos una pagina aleatoriamente para modificar
                while (true){
                     pos = r.nextInt(gestorMemoria.getPosUltPaginaColocada() + 1);
                     if (!gestorMemoria.getEstaClavado()[pos]) {
                        break;
                     }
                }
            //clavamos el bloque
                Pagina p = gestorMemoria.getBuffer()[pos];
                if(gestorMemoria.getModifico()[pos])
                    gestorMemoria.escribirPaginaEnDisco(p);
                gestorMemoria.clavarPagina(p);
                MostrarDatosDeDisco();
                MostrarDatosDeMemoria();
            }else{
                    JOptionPane.showMessageDialog(null,"Todos los bloques han sido clavados\n y se requiere que alguno se desclave..." ,"IMPORTANTE",0);
            }            
        } catch (Exception e) {
            JOptionPane.showMessageDialog(null,"No realizó los pasos previos para esta operación..." ,"ERROR",0);
        }
    }//GEN-LAST:event_btn_clavarMouseClicked

    private void btn_escribirMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_btn_escribirMouseClicked
        // TODO add your handling code here:
    }//GEN-LAST:event_btn_escribirMouseClicked

    private void btn_modificarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btn_modificarActionPerformed
         
    }//GEN-LAST:event_btn_modificarActionPerformed

    private void btn_borrarMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_btn_borrarMouseClicked
        // TODO add your handling code here:
    }//GEN-LAST:event_btn_borrarMouseClicked

    private void btn_borrarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btn_borrarActionPerformed
        numBloquesDisco = 0;
        numBloquesMemoria = 0;
        paginasDisco = null;
        paginasMemoria = null;
        modeloDisco.setNumRows(0);
        modeloMemoria.setNumRows(0);
        EstaEnMemoria = null;
        disco = null;
        gestorMemoria = null;
        txt_bloquesDisco.setText("");
        txt_bloquesMemoria.setText("");
        lbl_numPaginasMemoria.setText("");
    }//GEN-LAST:event_btn_borrarActionPerformed

    private void btn_desclavarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btn_desclavarActionPerformed
        try {
             //buscar un bloque desclavado
            //escoger aleatoriamente un bloque
            //ver si necesita actiualizar en disco
             boolean hay = false;
            for (int i = 0; i <= gestorMemoria.getPosUltPaginaColocada(); i++) {
                if (gestorMemoria.getEstaClavado()[i]) {
                    hay = true;
                    break;
                }
            }
            if (hay){
              int pos = 0;
                //buscamos una pagina aleatoriamente para desclavar
                while (true){
                     pos = r.nextInt(gestorMemoria.getPosUltPaginaColocada() + 1);
                     if (gestorMemoria.getEstaClavado()[pos]) {
                        break;
                     }
                }
            //desclavamos el bloque
                Pagina p = gestorMemoria.getBuffer()[pos];
                gestorMemoria.desclavarPagina(p);
                MostrarDatosDeDisco();
                MostrarDatosDeMemoria();
            }else{
                    JOptionPane.showMessageDialog(null,"Todos los bloques están desclavados\n y se requiere que alguno se clave..." ,"IMPORTANTE",0);
            }    
            
        } catch (Exception e) {
            JOptionPane.showMessageDialog(null,"No realizó los pasos previos para esta operación..." ,"ERROR",0);
        }
    }//GEN-LAST:event_btn_desclavarActionPerformed

    private void btn_escribirActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btn_escribirActionPerformed
        try {
              //buscar un bloque modificado
            //escoger aleatoriamente un bloque
             boolean hay = false;
            for (int i = 0; i <= gestorMemoria.getPosUltPaginaColocada(); i++) {
                if (gestorMemoria.getModifico()[i]) {
                    hay = true;
                    break;
                }
            }
            if (hay){
              int pos = 0;
                //buscamos una pagina aleatoriamente para desclavar
                while (true){
                     pos = r.nextInt(gestorMemoria.getPosUltPaginaColocada() + 1);
                     if (gestorMemoria.getModifico()[pos]) {
                        break;
                     }
                }
            //desclavamos el bloque
                Pagina p = gestorMemoria.getBuffer()[pos];
                gestorMemoria.escribirPaginaEnDisco(p);
                MostrarDatosDeDisco();
                MostrarDatosDeMemoria();
                String cola = gestorMemoria.getColaLRU().toString();
                lbl_numPaginasMemoria.setText(cola);
            }else{
                JOptionPane.showMessageDialog(null,"Todos los bloques no han sido modificados\n y se requiere que alguno se modifique..." ,"IMPORTANTE",0);
            }
        }
            catch (Exception e) {
            JOptionPane.showMessageDialog(null,"No realizó los pasos previos para esta operación..." ,"ERROR",0);
        }
    }//GEN-LAST:event_btn_escribirActionPerformed
    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(JFrameMemoriaIntemedia.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(JFrameMemoriaIntemedia.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(JFrameMemoriaIntemedia.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(JFrameMemoriaIntemedia.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                new JFrameMemoriaIntemedia().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btn_borrar;
    private javax.swing.JButton btn_clavar;
    private javax.swing.JButton btn_desclavar;
    private javax.swing.JButton btn_escribir;
    private javax.swing.JButton btn_modificar;
    private javax.swing.JButton btn_salir;
    private javax.swing.JButton btn_subirBloque;
    private javax.swing.JButton jButton1;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JLabel jLabel7;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JLabel lbl_numPaginasMemoria;
    private javax.swing.JTable tabla_disco;
    private javax.swing.JTable tabla_memoria;
    private javax.swing.JTextField txt_bloquesDisco;
    private javax.swing.JTextField txt_bloquesMemoria;
    // End of variables declaration//GEN-END:variables
}
